package com.haulmont.asu.web.ui.commission_composition_command;

import com.haulmont.asu.entity.Commission;
import com.haulmont.asu.entity.CommissionCompositionCommand;
import com.haulmont.asu.entity.CommissionMember;
import com.haulmont.cuba.gui.components.AbstractEditor;
import com.haulmont.cuba.gui.components.LookupField;
import com.haulmont.cuba.gui.data.CollectionDatasource;
import com.haulmont.cuba.gui.data.Datasource;
import com.haulmont.cuba.gui.data.impl.DsListenerAdapter;

import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Author: Sergey42
 * Date: 28.11.13 14:36
 */
public class CommissionCompositionCommandEditor
        extends AbstractEditor<CommissionCompositionCommand> {

    @Inject
    protected CollectionDatasource<CommissionMember, UUID> memberDs;
    @Inject
    protected CollectionDatasource<Commission, UUID> commissionDs;
    @Inject
    protected LookupField commissionLF;

    @Override
    public void init(Map<String, Object> params) {
        commissionLF.setNullOption(null);
    }

    @Override
    protected void postInit() {
        if (getItem().getCommission() != null) {
            refreshMemberDs();
        }
        commissionDs.addListener(new DsListenerAdapter<Commission>() {
            @Override
            public void itemChanged(Datasource<Commission> ds, @Nullable Commission prevItem, @Nullable Commission item) {
                memberDs.clear();

                if (item != null) {
                    List<CommissionMember> members = item.getMembers();
                    if (members != null) {
                        for (CommissionMember member : members) {
                            memberDs.addItem(member);
                        }
                    }
                }
            }
        });

    }

    protected void refreshMemberDs() {
        memberDs.setQuery("select m from ext$CommissionMember m where m.commission.id = :custom$id");
        memberDs.refresh(Collections.<String, Object>singletonMap("id", getItem().getCommission().getId()));
    }
}
